﻿
var vm = new Vue({
    el: '#app',
    data: function () {
        return {
            pagename: "生产质检",
            common_fn: null,
            userinfo: null,
            mainTable_maxHeight: 0,
            loading: false,
            //订单
            orderData: [],
            selectedOrderID: "",
            selectedOrderNo: "",
            selectedProductioScheduleID: "",//选中的订单对应的批次计划ID
            // 质检列表
            param: "",
            inspectionData: [],
            inspectiondataLength: 0,
            inspect_row: "",
            inspect_index: 0,
            //质检填写框
            inspectionDialog: false,
            rejectsquantity: 0,//不良数量
        }
    },
    methods: {
        tableRowClassName({ row, rowIndex }) {
            return 'success-row';
        },
        // 获取所有订单
        getOrders: function () {
            var self = this;
            self.loading = true;
            var filters = [{
                "classFlag": 1,
                "classType": "MesOrderSheet",
                "propName": "state",
                "op": 4,
                "propValue": "3",      //已排产发布的订单
                "propValue2": "",
                "logic": 0,
                "leftSplitter": 0,
                "rightSplitter": 0,
                "bAddWhereClauseFlag": true
            }];
            self.common_fn.queryObject("MesOrderSheet", filters, self.userinfo, function (response) {
                if (response.resFlag == 0) {
                    for (i = response.result.length - 1; i >= 0; i--) {
                        response.result[i].properties.state == 0 ? response.result[i].properties['state_name'] = '待审核' : response.result[i].properties.state == 1 ? response.result[i].properties['state_name'] = '审核中' : response.result[i].properties['state_name'] = '已发布';
                        response.result[i].properties.deliverydate = response.result[i].properties.deliverydate.split(' ')[0];
                        response.result[i].properties.creationdate = response.result[i].properties.creationdate.split(' ')[0]; //APP加
                        response.result[i].properties.orderquantity = Number(response.result[i].properties.orderquantity);
                        self.orderData.push({
                            "id": response.result[i].id,
                            "name": response.result[i].properties.name,
                        })
                    }
                    self.orderData = response.result;
                    if (self.orderData.length !== 0) {
                        self.selectedOrderNo = self.orderData[self.orderData.length - 1].properties.orderno;
                        self.selectedOrderID = self.orderData[self.orderData.length - 1].id
                        self.getProductioSchedule(self.selectedOrderID);
                    }
                } else {
                    notify(response.errMsg, 'error')
                }
                self.loading = false;
            })
        },
        //获取批次计划ID
        getProductioSchedule: function (selectedOrderID) {
            var self = this;
            self.loading = true;
            var param = {
                "appName": "mes",
                "sql": "select * from MES_ORDERSHEETPRODUCT where A_OBJID = " + selectedOrderID
            };
            self.common_fn.sqlFn(param, function (response) {
                if (response.resFlag == 0) {
                    self.selectedProductioScheduleID = parseInt(response.result[0].properties.b_objid)
                    self.getData(self.selectedProductioScheduleID)
                } else {
                    notify(response.errMsg, 'error')
                }
            })
        },
        getData: function (productionScheduleID) {
            var self = this;
            self.loading = true;
            var param = {
                "filters": [{
                    "classFlag": 1,
                    "classType": "MesReportSheet",
                    "propName": "product_objid",
                    "op": 7,
                    "propValue": productionScheduleID + '',
                    "propValue2": "",
                    "logic": 0,
                    "leftSplitter": 0,
                    "rightSplitter": 0,
                    "bAddWhereClauseFlag": true
                }],
                "orderItems": [],
                "queryclasses": ["MesReportSheet", "MesProductionSchedule", "PlmPart", "SysPerson", "QcpProcess", "MesSemiFinished", "SysSnapshot", "MesOrderSheet"],
                "queryFields": [],
                "isQueryPreNext": true,
                "isQueryNextConsiderParent": true,
                "user": self.userinfo.user
            }
            self.common_fn.invoke('JridgeMesSTD_AdditionalService.dll', "JridgeMesSTD_AdditionalService.ReportWorkCheckMgr", "QueryQualityInspectOneSet", param, self.userinfo, function (response) {
                if (response.resFlag == 0) {
                    self.inspectionData = [];
                    self.inspectiondataLength = response.result.items.length;
                    for (var i = 0; i < response.result.items.length; i++) {
                        response.result.items[i]['properties'] = {};
                        for (var k = 0; k < response.result.items[i].itemObjects.length; k++) {
                            response.result.items[i].properties[response.result.items[i].itemObjects[k].type] = response.result.items[i].itemObjects[k].properties;
                            response.result.items[i].properties[response.result.items[i].itemObjects[k].type]['id'] = response.result.items[i].itemObjects[k].id;
                        }
                    }
                    var inspectionDataTemp = [];
                    for (var i = 0; i < response.result.items.length; i++) {
                        inspectionDataTemp.push({
                            "mesreportsheet": response.result.items[i].properties.mesreportsheet,
                            "mesreportsheet_id": response.result.items[i].properties.mesreportsheet.id,
                            "productlayer": response.result.items[i].properties.messemifinished.productlayer,  //生产层
                            "productname": response.result.items[i].properties.mesproductionschedule.name,
                            "processno": response.result.items[i].properties.qcpprocess.processno,  //工序号
                            "qcpname": response.result.items[i].properties.qcpprocess.name,//工序名称
                            "materialno": response.result.items[i].properties.plmpart.materialno,
                            "identityno": response.result.items[i].properties.plmpart.identityno,
                            "plmpartname": response.result.items[i].properties.plmpart.name,  //零件名称
                            "assignquantity": response.result.items[i].properties.mesreportsheet.assignquantity,
                            "realquantity": response.result.items[i].properties.mesreportsheet.realquantity,
                            "reporter": response.result.items[i].properties.mesreportsheet.reportor,
                            "reporttime": response.result.items[i].properties.mesreportsheet.reporttime,
                            "firstquantity": response.result.items[i].properties.mesreportsheet.realquantity, //合格品数量
                            "rejectsquantity": response.result.items[i].properties.mesreportsheet.rejectsquantity, //不合格品数量
                        })
                    }
                    //排序
                    for (var i = 0; i < inspectionDataTemp.length; i++) {
                        for (var j = 0; j < inspectionDataTemp.length - 1 - i; j++) {
                            if (inspectionDataTemp[j].productlayer < inspectionDataTemp[j + 1].productlayer) {
                                var temp = inspectionDataTemp[j + 1];
                                inspectionDataTemp[j + 1] = inspectionDataTemp[j];
                                inspectionDataTemp[j] = temp;
                            }
                        }
                    }
                    self.inspectionData = inspectionDataTemp;
                    self.loading = false
                } else {
                    notify(response.errMsg, 'error')
                }
                self.loading = false;
            })
        },
        //选择某个订单
        selectOrder: function () {
            this.getProductioSchedule(this.selectedOrderID)
        },

        //质检
        inspect: function (index, row) {
            if (index == 0) {
                var self = this;
                //当前选中的质检工单
                self.inspect_row = row;
                self.inspect_index = index;
                self.inspect_row.unqualifiedArray = [];
                self.inspect_row.unqualifiedArray.push(
                    {
                        "id": 0,
                        "type": "MesQACheckItem",
                        "properties": {
                            "name": null,
                            "creator": null,
                            "creationdate": null,
                            "description": '',//不合格品描述
                            "repairreason": '',//不合格品现象
                            "repairmode": null,//处理结果
                            "checkpoint": null,
                            "repairquantity": null,
                            "wastequantity": null,
                            "wastereason": null,
                            "part_objid": null,
                            "process_objid": null,
                            "order_objid": null,
                            "product_objid": null
                        }
                    }
                );
                self.inspect_row.defect_items = [];
                //根据工序编号获取Qcp_Defect
                var sql = {
                    sql: "select * from Qcp_Defect",
                    appName: "mes"
                }
                self.common_fn.sqlFn(sql, function (response) {
                    if (response.resFlag == 0) {
                        self.inspect_row.defect_items = response.result;
                        self.inspect_row = JSON.parse(JSON.stringify(self.inspect_row));
                        self.inspectionDialog = true;
                    }
                })
            } else {
                message('请先将前道工序质检完成！', 'error');
            }

        },

        //自动计算合格数量  
        computefirstquantity: function () {
            var self = this;
            self.inspect_row.rejectsquantity = self.rejectsquantity;
            if (Number(self.inspect_row.rejectsquantity) > Number(self.inspect_row.realquantity)) {
                self.inspect_row.rejectsquantity = self.inspect_row.realquantity;
                self.rejectsquantity = self.inspect_row.rejectsquantity;
            }
            self.inspect_row.firstquantity = self.inspect_row.realquantity - self.inspect_row.rejectsquantity;
            self.inspect_row = JSON.parse(JSON.stringify(self.inspect_row));
        },

        //新添不合格信息
        addUnqualifiedList: function () {
            this.inspect_row.unqualifiedArray.push(
                {
                    "id": 0,
                    "type": "MesQACheckItem",
                    "properties": {
                        "name": null,
                        "creator": null,
                        "creationdate": null,
                        "description": '',//不合格品描述
                        "repairreason": '',//不合格品现象
                        "repairmode": null,//处理结果
                        "checkpoint": null,
                        "repairquantity": null,
                        "wastequantity": null,
                        "wastereason": null,
                        "part_objid": null,
                        "process_objid": null,
                        "order_objid": null,
                        "product_objid": null
                    }
                }
            );
            this.inspect_row = JSON.parse(JSON.stringify(this.inspect_row))
            Vue.nextTick(function () {
                $('.select_write input').attr('readOnly', false)
            })

        },
        //删除不合格信息
        deleteList: function (index) {
            this.inspect_row.unqualifiedArray.splice(index, 1);
        },
        select_write_fn: function (e, item) {
            item.properties.repairreason = e.target.value;
        },
        // 质检
        submitInspection: function () {
            var self = this;
            var MesReportSheetObj = {
                "id": Number(self.inspect_row.mesreportsheet_id),
                "type": "MesReportSheet",
                "properties": {}
            };
            for (var i = 0; i < self.MesReportSheetClassMeta.Class.Properties.Property.length; i++) {
                MesReportSheetObj.properties[self.MesReportSheetClassMeta.Class.Properties.Property[i]['@internalName'].toLowerCase()] = self.inspect_row.mesreportsheet[self.MesReportSheetClassMeta.Class.Properties.Property[i]['@internalName'].toLocaleLowerCase()];
            }
            self.repairquantity = 0;
            var unqualifiedArray = [];
            for (var i = 0; i < self.inspect_row.unqualifiedArray.length; i++) {
                if (Number(self.inspect_row.unqualifiedArray[i].properties.repairquantity) == 0) {
                    //如果数量为0，不要添加到提交
                    continue;
                }
                if (Number(self.inspect_row.unqualifiedArray[i].properties.repairquantity) != 0 && self.inspect_row.unqualifiedArray[i].properties.repairreason == '') {
                    notify_timeOut('不合格品详情请填写完整！', 'error')
                    return
                }
                if (self.inspect_row.unqualifiedArray[i].properties.repairquantity !== '') {
                    self.repairquantity = self.repairquantity + Number(self.inspect_row.unqualifiedArray[i].properties.repairquantity);
                }
                unqualifiedArray.push(self.inspect_row.unqualifiedArray[i]);
            }
            if (self.inspect_row.firstquantity === '') {
                self.inspect_row.firstquantity = 0;
            }
            if (unqualifiedArray.length > 0 && (self.inspect_row.rejectsquantity == '' || self.inspect_row.rejectsquantity == '0')) {
                notify_timeOut('请填写不良数量', 'error');
                return
            }
            if (self.inspect_row.firstquantity < 0) {
                notify_timeOut("合格数量不能小于0，请重新输入", 'error');
                return;
            }
            //报工数量就是合格数量
            MesReportSheetObj.properties.realquantity = self.inspect_row.firstquantity + self.inspect_row.rejectsquantity;
            var param = {
                "appName": "MES",
                "connectionId": 2,
                "qaTableItems": unqualifiedArray,
                "reportSheets": [MesReportSheetObj],
                "user": self.userinfo.user
            }
            self.common_fn.invoke('JridgeMesSTD_AdditionalService.dll', "JridgeMesSTD_AdditionalService.ReportWorkCheckMgr", "QualityInspectDirectly", param, self.userinfo, function (response) {
                if (response.resFlag == 0) {
                    // 将总不合格数量保存到质检单上
                    var sql = {
                        "appName": "mes",
                        "sql": "update MES_QATABLE set UnqualifiedQuantity = '" + self.inspect_row.rejectsquantity + "' where OBJID = '" + response.result.id + "'"
                    }
                    self.common_fn.sqlFn(sql, function (res) {
                        if (response.resFlag != 0) {
                            notify(res.errMsg, 'error')
                        } else {
                            self.inspectionDialog = false;
                            response.result.properties.unqualifiedquantity = self.inspect_row.rejectsquantity;
                            //质检单对象
                            self.inspect_row['relationnode'] = response.result;
                            self.inspectionData.splice(self.inspect_index, 1);
                            self.inspectiondataLength = self.inspectiondataLength - 1;
                            if (self.inspectiondataLength == 0) {
                                //state 置为4 ，mesproductionschedule state自动变为5
                                var param = {
                                    "appName": "mes",
                                    "sql": "update MES_OrderSheet set state = 4 where objid = " + self.selectedOrderID
                                }
                                self.common_fn.sqlFn(param, function (response) {
                                    if (response.resFlag == 0) {
                                        message('质检成功，该订单已全部完成！', 'success')
                                    } else {
                                        notify(response.errMsg, 'error')
                                    }
                                })
                            } else {
                                message('质检成功', 'success')
                            }
                        }
                    })
                } else {
                    notify(response.errMsg, 'error');
                }
            })
        },
    },
    mounted: function () {
        var self = this;
        self.common_fn = new common_fn();
        self.common_fn.init(function () {
            self.common_fn.UserInfo(function (response) {
                if (response.user == null) {
                    window.location.href = 'login.html?redirect=inspection.html';
                }
                self.userinfo = response;
                self.common_fn.CheckFunction(self.userinfo, 'mes', 'mes', 'QualityInspect', '', '', 'inspection', function () { })
                self.getOrders();
                /*获取MesReportSheetClassMeta*/
                axios.get('../design/loadClassJson?name=MesReportSheet')
                    .then(function (response) {
                        if (typeof (response.data) == 'string') {
                            response.data = JSON.parse(response.data);
                        }
                        if (response.status == '200') {
                            self.MesReportSheetClassMeta = response.data.ClassMeta;
                        }
                    })
            })
        });
    },
    watch: {
        'rejectsquantity': function (newvalue, oldvalue) {
            this.computefirstquantity();
        }
    }
})
window.onload = function () {
    if (vm.mainTable_maxHeight != null || vm.mainTable_maxHeight != undefined) {
        window.setTimeout(function () {
            vm.mainTable_maxHeight = $(window).height() - 150;
        }, 100)
    }
}


